package com.tensquare.manager.filter;

import com.netflix.discovery.converters.Auto;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.RequestContextUtils;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2019/9/25 9:57
 * 后端网关过滤器
 */
@Component
public class ManagerZuulFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.得到当前请求的上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2.得到请求对象
        HttpServletRequest request = requestContext.getRequest();
        //2.1)对方法名为OPTIONS的请求进行放于
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        //2.2)如果当前正在登录，则需要放行
        if(request.getRequestURL().toString().contains("login")){
            return null;
        }
        //3.得到请求头对象
        String header = request.getHeader("Authorization");
        //4.判断是否有值
        if(StringUtils.isNotBlank(header) && header.startsWith("Bearer ")){ //判断是否以Bearer 开头
                //4.1)得到第七位开始后的内容，就是token
                String token = header.substring(7);
                //4.2)解析token
                Claims claims = jwtUtil.parseJwt(token);
                //4.3)如果存在此对象
                if(claims != null){
                    //4.4)取得其中的roles信息
                    String roles = (String) claims.get("roles");
                    //4.5)判断是否是admin角色，如果是就向将请求头放到当前的过滤器向下传递
                    if(StringUtils.isNotBlank(roles) && "admin".equals(roles)){
                        requestContext.addZuulRequestHeader("Authorization",header);
                        System.out.println("将我们自己的请求头添加到网关的请求头中，" + header);
                        return null;
                    }
                }
        }
        //5.阻止向下传递
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(403);
        requestContext.setResponseBody("无权访问！");
        requestContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
